local skynet = require "skynet"
local db   = require "dblib"
local CMD = require "main_proto"
local CMDGAME = require "game_proto"
local Sraw = require "stable.raw"
local bufferrw = require "buffrw"
local buffwrite = bufferrw.BuffWrite
local buffread  = bufferrw.BuffRead

Sraw.init()
local QueryStr = require("core").QueryStr

local function SendData(addr,msg)
	skynet.send(math.floor(addr),"lua","send_data",msg)
end
local lobby = {}
--钻石兑换老友豆
function lobby.ChangeJinBiReq(smsg,player)
	local nDiamondCount = string.unpack("I4",smsg,5)
	if tonumber(player.nDiamond) < nDiamondCount then
		return
	end

	local nCoins = nDiamondCount * 1000


	if lobby.AddOrSubPlayerDiamond(player,-nDiamondCount,"兑换 余额 :"..tostring(player.nDiamond)) then
		lobby.AddOrSubPlayerJinBi(player,nCoins,"兑换 余额 :"..tostring(player.nDiamond))
	else
		return
	end

	skynet.error("player.nDiamond = ",player.nDiamond," player.llJinBi = ",player.llJinBi)
	local msg = string.pack(">I2>I2<I4I4I4I8I4",CMD.Main_ClientAndGameSvr_UserModle,CMD.Sub_GameSvrToClient_UserModle_PlayerBasicUpdate,
		math.floor(player.nPlayerId),player.nDiamond,player.nScore,player.llJinBi,player.nExternCode)
	SendData(player.nAgentAddr,msg)

	msg = string.pack(">I2>I2<c96",CMD.Main_ClientAndGameSvr_UserModle,CMD.Sub_GameSvrToClient_UserModle_HingMsg,"兑换老友豆成功")
	SendData(player.nAgentAddr,msg)
end
--增减金币
function lobby.AddOrSubPlayerJinBi(player,nCount,szMsg)
	if nCount == 0 then return end
	if nCount < 0 then
		if player.llJinBi < math.abs(nCount) then return false end
	end
	player.llJinBi = player.llJinBi + nCount
	QueryStr:Clean()
	QueryStr:AddStr("call Pr_AddOrSubPlayerJinBi(")
	QueryStr:AddStr(math.floor(player.nPlayerId))
	QueryStr:AddStr(nCount)
	QueryStr:AddStr(")")
	db.call(QueryStr.str)
	--增减金币日志
	QueryStr:Clean()
	QueryStr:AddStr("call Pr_UserGoldActionLog(")
	QueryStr:AddStr(math.floor(player.nPlayerId))
	QueryStr:AddStr(player.szName)
	QueryStr:AddStr(nCount)
	QueryStr:AddStr(szMsg)
	QueryStr:AddStr(")")
	db.call(QueryStr.str)
	return true
end

--增减钻石
function lobby.AddOrSubPlayerDiamond(player,nDiamondCount,szMsg)
	if nDiamondCount == 0 then return end
	if nDiamondCount < 0 then
		if player.nDiamond < math.abs(nDiamondCount) then return false end
	end
	player.nDiamond = player.nDiamond + nDiamondCount
	QueryStr:Clean()
	QueryStr:AddStr("call Pr_AddOrSubPlayerDiamond(")
	QueryStr:AddStr(math.floor(player.nPlayerId))
	QueryStr:AddStr(nDiamondCount)
	QueryStr:AddStr(")")
	db.call(QueryStr.str)
	--增减钻石日志
	QueryStr:Clean()
	QueryStr:AddStr("call Pr_UserDiamondActionLog(")
	QueryStr:AddStr(math.floor(player.nPlayerId))
	QueryStr:AddStr(player.szName)
	QueryStr:AddStr(nDiamondCount)
	QueryStr:AddStr(szMsg)
	QueryStr:AddStr(")")
	db.call(QueryStr.str)

	return true
end

function lobby.BuyDiamondReq(smsg,player)
	local szPrepayNo = string.unpack("c128")

	QueryStr:Clean()
	QueryStr:AddStr("call Pr_PayGetDiamond(")
	QueryStr:AddStr(math.floor(player.nPlayerId))
	QueryStr:AddOutParam("@intOutTotalDiamond")
	QueryStr:AddOutParam("@returnVal")
	QueryStr:AddStr(")")
	db.call(QueryStr.str)

	local res1,res2 = db.call(QueryStr.str,"select @intOutTotalDiamond,@returnVal")

	if res2 and res2[1] then
		local nOuTotalDiamond = res2[1]['@intOutTotalDiamond']
		local nAddDiamond = nOuTotalDiamond - math.floor(player.nDiamond)
		msg = string.pack(">I2>I2<c96",CMD.Main_ClientAndGameSvr_UserModle,CMD.Sub_GameSvrToClient_UserModle_HingMsg,"已成功购买 "..nAddDiamond.." 钻石")
		SendData(player.nAgentAddr,msg)
		
		player.nDiamond = nAddDiamond
		lobby.UpdatePlayerBasicInfo(player)
	else
		msg = string.pack(">I2>I2<c96",CMD.Main_ClientAndGameSvr_UserModle,CMD.Sub_GameSvrToClient_UserModle_HingMsg,"system error")
		SendData(player.nAgentAddr,msg)
	end
	
end

function lobby.ZhanjiReq(player)
	local function QueryZhanJi(playId)
		QueryStr:Clean()
		QueryStr:AddStr("call Pr_LoadZhanJi5(")
		QueryStr:AddStr(math.floor(playId))
		QueryStr:AddStr(")")
		local res = db.call(QueryStr.str)

		local result = {nPlayerId = nil, nCount = nil, OneZhanJiList = {}, bSucc = nil}
	    if #res[1] == 0 then  -- 返回列表长度
	        result.bSucc = false
	        return result
	    end

	    local count = 0    
	    result.nPlayerId = play_id
	    for index,table_obj in pairs(res[1]) do 
	        count = count + 1
	        local OneZhanJi = {nIdx = nil, nTableId = nil, wMyChairId = nil, nRound = nil, nGameId = nil, szTime = nil,szNames = {}, nScores = {}}
	        OneZhanJi['nIdx'] = table_obj['@intOutIdx']
	        OneZhanJi['nTableId'] = table_obj['@intOutTableId']
	        OneZhanJi['wMyChairId'] = table_obj['@intOutMyChair']
	        OneZhanJi['nRound'] = table_obj['@intTotalRound']
	        OneZhanJi['nGameId'] = table_obj['@intOutGameID']        
	        OneZhanJi['szTime'] = table_obj['@szOutTime']
	        table.insert(OneZhanJi.szNames,table_obj['@szChair0Name'])
	        table.insert(OneZhanJi.szNames,table_obj['@szChair1Name'])
	        table.insert(OneZhanJi.szNames,table_obj['@szChair2Name'])
	        table.insert(OneZhanJi.szNames,table_obj['@szChair3Name'])
	        table.insert(OneZhanJi.szNames,table_obj['@szChair4Name'])
	        table.insert(OneZhanJi.szNames,table_obj['@szChair5Name'])
	        table.insert(OneZhanJi.szNames,table_obj['@szChair6Name'])
	        table.insert(OneZhanJi.szNames,table_obj['@szChair7Name'])
	        
	        table.insert(OneZhanJi.nScores,table_obj['@intChair0Score'])
	        table.insert(OneZhanJi.nScores,table_obj['@intChair1Score'])
	        table.insert(OneZhanJi.nScores,table_obj['@intChair2Score'])
	        table.insert(OneZhanJi.nScores,table_obj['@intChair3Score'])
	        table.insert(OneZhanJi.nScores,table_obj['@intChair4Score'])
	        table.insert(OneZhanJi.nScores,table_obj['@intChair5Score'])
	        table.insert(OneZhanJi.nScores,table_obj['@intChair6Score'])
	        table.insert(OneZhanJi.nScores,table_obj['@intChair7Score'])
	        table.insert(result.OneZhanJiList,OneZhanJi)
	    end
	    result.nCount = count
	    result.bSucc = true    
	    return result
	end

	local result = QueryZhanJi(player.nPlayerId)
	print(result.nCount)
	local BuffWrite = buffwrite.new()
    BuffWrite:proto(CMD.Main_ClientAndGameSvr_UserModle, CMD.Sub_GameSvrToClient_UserModle_ZhanJi)
    if result.bSucc then         
        BuffWrite:int4(result.nCount)        
        for k , OneZhanJi in pairs(result.OneZhanJiList) do
            BuffWrite:int4(OneZhanJi.nIdx)
            BuffWrite:int4(OneZhanJi.nTableId)
            BuffWrite:int4(OneZhanJi.nRound)           
            BuffWrite:int4(OneZhanJi.nGameId)
            BuffWrite:int2(OneZhanJi.wMyChairId)
            
            for i = 1, 8 do
                BuffWrite:int4(OneZhanJi.nScores[i])
            end
            for i = 1, 8 do
                BuffWrite:str(OneZhanJi.szNames[i],64)
            end            
            BuffWrite:str(OneZhanJi.szTime,32)           
        end        
    end
    SendData(player.nAgentAddr,BuffWrite.buff)
end
--代理开房数据库记录
function lobby.AddAgentRoom(pReq)
	QueryStr:Clean()
	QueryStr:AddStr("call pr_AgentCreateTable2(")
	QueryStr:AddStr(math.floor(pReq.nPlayerID))
	QueryStr:AddStr(math.floor(pReq.nTableID))
	QueryStr:AddStr(math.floor(pReq.nGameID))
	QueryStr:AddStr(math.floor(pReq.nMode))
	QueryStr:AddStr(math.floor(pReq.nPlayerCount))
	QueryStr:AddStr(math.floor(pReq.nRound))
	QueryStr:AddStr(math.floor(pReq.nCost))
	QueryStr:AddStr(pReq.szRoomInfo)
	QueryStr:AddOutParam("@returnVal")
	QueryStr:AddOutParam("@r")
	QueryStr:AddStr(")")
	local res1,res2 = db.call(QueryStr.str,"select @returnVal,@r")
	local pResp = {}
	pResp.nPlayerID = math.floor(pReq.nPlayerID)
    pResp.nTableID  = math.floor(pReq.nTableID)
    pResp.nResult = 1;
    if res2[1]['@returnVal'] then
    	pResp.nResult = res2[1]['@returnVal']
    else
    	pResp.nResult = -1;
	end
	return pResp
end

--代理解散房间
function lobby.OnAgentDismissTable(nRoomId,nAgentID)
	QueryStr:Clean()
	QueryStr:AddStr("call pr_AgentDismissTable(")
	QueryStr:AddStr(math.floor(nAgentID))
	QueryStr:AddStr(math.floor(nRoomId))
	QueryStr:AddOutParam("@returnVal")
	QueryStr:AddOutParam("@r")
	QueryStr:AddStr(")")
	local res1,res2 = db.call(QueryStr.str,"select @returnVal,@r")
	local result = 0
	if res2 then
		result = res2[1]['@returnVal']
	end
	local pResp = {}
	pResp.nPlayerID    = nAgentID
    pResp.nTableID     = nRoomId
    pResp.nResult 	= result
    return pResp
end

function lobby.UpdatePlayerBasicInfo(player)
	local msg = string.pack(">I2>I2<I4I4I4I8I4",
		CMD.Main_ClientAndGameSvr_UserModle,CMD.Sub_GameSvrToClient_UserModle_PlayerBasicUpdate,
		math.floor(player.nPlayerId),math.floor(player.nDiamond),math.floor(player.nScore),math.floor(player.llJinBi),math.floor(player.nExternCode or 0))
	SendData(player.nAgentAddr,msg)
end
--更新用户信息
function lobby.OnUserUpdateInfo(player)
	QueryStr:Clean()
	QueryStr:AddStr("call Pr_UserGetDiamondAndJinBi(")
	QueryStr:AddStr(math.floor(player.nPlayerId))
	QueryStr:AddOutParam("@nDiamond")
	QueryStr:AddOutParam("@nJinBi")
	QueryStr:AddOutParam("@returnVal")
	QueryStr:AddStr(")")
	local res1,res2 = db.call(QueryStr.str,"select @nDiamond,@nJinBi,@returnVal")
	player.nDiamond = res2[1]['@nDiamond']
	player.llJinBi = res2[1]['@nJinBi']
	lobby.UpdatePlayerBasicInfo(player)
end

function lobby.OnNetGetUserPhoneInformation(player)
	local bReg = 0
	QueryStr:Clean()
	QueryStr:AddStr("call Pr_GetUserPhone(")
	QueryStr:AddStr(math.floor(player.nPlayerId))
	QueryStr:AddOutParam("@phone")
	QueryStr:AddOutParam("@returnVal")
	QueryStr:AddStr(")")
	local res1,res2 = db.call(QueryStr.str,"select @phone,@returnVal")
	if res2 and res2[1] then
		bReg = 1
	end
	local msg = string.pack(">I2>I2<I1",
		CMD.Main_ClientAndGameSvr_UserModle,CMD.Sub_GameSvrToClient_UserModle_UserInformation,bReg)
	SendData(player.nAgentAddr,msg)
end
--写总战绩
function lobby.WriteZhanJiDb(pData)
	QueryStr:Clean()
	QueryStr:AddStr("call Pr_WriteZhanJi3(")
	QueryStr:AddStr(math.floor(pData.nPlayerId))
	QueryStr:AddStr(tonumber(pData.nGameId))
	QueryStr:AddStr(pData.nTableId)
	QueryStr:AddStr(pData.nGameRound)
	QueryStr:AddStr(pData.nTotalRound)
	QueryStr:AddStr(pData.wMyChairId)
	QueryStr:AddStr(pData.nScores[1])
	QueryStr:AddStr(pData.nScores[2])
	QueryStr:AddStr(pData.nScores[3])
	QueryStr:AddStr(pData.nScores[4])
	QueryStr:AddStr(pData.nScores[5])
	QueryStr:AddStr(pData.nScores[6])
	QueryStr:AddStr(pData.nScores[7])
	QueryStr:AddStr(pData.nScores[8])
	QueryStr:AddStr(pData.szNames[1])
	QueryStr:AddStr(pData.szNames[2])
	QueryStr:AddStr(pData.szNames[3])
	QueryStr:AddStr(pData.szNames[4])
	QueryStr:AddStr(pData.szNames[5])
	QueryStr:AddStr(pData.szNames[6])
	QueryStr:AddStr(pData.szNames[7])
	QueryStr:AddStr(pData.szNames[8])
	QueryStr:AddStr(pData.szTime)
	QueryStr:AddOutParam("@intOutIdx")
	QueryStr:AddOutParam("@returnVal")
	QueryStr:AddStr(")")
	skynet.error("写总战绩",QueryStr.str)
	local res1,res2 = db.call(QueryStr.str,"select @intOutIdx,@returnVal")
end

function lobby.OnAgentTableStatus(pReq)
	QueryStr:Clean()
	QueryStr:AddStr("call pr_AgentSetTableStatus(")
	QueryStr:AddStr(math.floor(pReq.nPlayerID))
	QueryStr:AddStr(math.floor(pReq.nTableID))
	QueryStr:AddStr(math.floor(pReq.nStatus))
	QueryStr:AddOutParam("@returnVal")
	QueryStr:AddOutParam("@r")
	QueryStr:AddStr(")")
	local res1,res2 = db.call(QueryStr.str,"select @returnVal,@r")

	if res2 and res2[1]['@returnVal'] == 1 then
		return true
	end

	return false
end

--写分战绩
function lobby.WriteUserZhanJi(pReg)
	skynet.error("数据库写战绩")
	QueryStr:Clean()
	QueryStr:AddStr("call Pr_WriteUserZhanJi3(")
	QueryStr:AddStr(pReg.nGameId)
	QueryStr:AddStr(pReg.nTableId)
	QueryStr:AddStr(pReg.nPlayerId)
	QueryStr:AddStr(pReg.szNickName)

	QueryStr:AddStr(pReg.szStarTime)
	QueryStr:AddStr(pReg.szEndTime)
	QueryStr:AddStr(pReg.szRecToken)
	QueryStr:AddStr(pReg.nDiFen)
	QueryStr:AddStr(pReg.jushu)
	QueryStr:AddStr(pReg.nTotalJu)
	QueryStr:AddStr(pReg.fuju)
	QueryStr:AddStr(pReg.fuType)
	QueryStr:AddStr(pReg.fuFangShi)
	QueryStr:AddStr(pReg.zhangjia)

	QueryStr:AddStr(pReg.nPlayerIdArr[1] or 0)
	QueryStr:AddStr(pReg.nArrowArr[1] or 0)
	QueryStr:AddStr(pReg.nScores[1] or 0)
	QueryStr:AddStr(pReg.szNames[1] or "")

	QueryStr:AddStr(pReg.nPlayerIdArr[2] or 0)
	QueryStr:AddStr(pReg.nArrowArr[2] or 0)
	QueryStr:AddStr(pReg.nScores[2] or 0)
	QueryStr:AddStr(pReg.szNames[2] or "")

	QueryStr:AddStr(pReg.nPlayerIdArr[3] or 0)
	QueryStr:AddStr(pReg.nArrowArr[3] or 0)
	QueryStr:AddStr(pReg.nScores[3] or 0)
	QueryStr:AddStr(pReg.szNames[3] or "")

	QueryStr:AddStr(pReg.nPlayerIdArr[4] or 0)
	QueryStr:AddStr(pReg.nArrowArr[4] or 0)
	QueryStr:AddStr(pReg.nScores[4] or 0)
	QueryStr:AddStr(pReg.szNames[4] or "")

	QueryStr:AddStr(pReg.nPlayerIdArr[5] or 0)
	QueryStr:AddStr(pReg.nArrowArr[5] or 0)
	QueryStr:AddStr(pReg.nScores[5] or 0)
	QueryStr:AddStr(pReg.szNames[5] or "")

	QueryStr:AddStr(pReg.nPlayerIdArr[6] or 0)
	QueryStr:AddStr(pReg.nArrowArr[6] or 0)
	QueryStr:AddStr(pReg.nScores[6] or 0)
	QueryStr:AddStr(pReg.szNames[6] or "")

	QueryStr:AddStr(pReg.nPlayerIdArr[7] or 0)
	QueryStr:AddStr(pReg.nArrowArr[7] or 0)
	QueryStr:AddStr(pReg.nScores[7] or 0)
	QueryStr:AddStr(pReg.szNames[7] or "")

	QueryStr:AddStr(pReg.nPlayerIdArr[8] or 0)
	QueryStr:AddStr(pReg.nArrowArr[8] or 0)
	QueryStr:AddStr(pReg.nScores[8] or 0)
	QueryStr:AddStr(pReg.szNames[8] or "")

	QueryStr:AddStr(pReg.mingGanArr[1] or 0)
	QueryStr:AddStr(pReg.mingGanArr[2] or 0)
	QueryStr:AddStr(pReg.mingGanArr[3] or 0)
	QueryStr:AddStr(pReg.mingGanArr[4] or 0)
	QueryStr:AddStr(pReg.mingGanArr[5] or 0)
	QueryStr:AddStr(pReg.mingGanArr[6] or 0)
	QueryStr:AddStr(pReg.mingGanArr[7] or 0)
	QueryStr:AddStr(pReg.mingGanArr[8] or 0)

	QueryStr:AddStr(pReg.anganArr[1] or 0)
	QueryStr:AddStr(pReg.anganArr[2] or 0)
	QueryStr:AddStr(pReg.anganArr[3] or 0)
	QueryStr:AddStr(pReg.anganArr[4] or 0)
	QueryStr:AddStr(pReg.anganArr[5] or 0)
	QueryStr:AddStr(pReg.anganArr[6] or 0)
	QueryStr:AddStr(pReg.anganArr[7] or 0)
	QueryStr:AddStr(pReg.anganArr[8] or 0)

	QueryStr:AddStr(pReg.wMyChairId)
	QueryStr:AddStr(pReg.bEndJu)

	QueryStr:AddOutParam("@intOutIdx")
	QueryStr:AddOutParam("@returnVal")
	skynet.error("写数据库完成",QueryStr.str)
	QueryStr:AddStr(")")
	local res1,res2 = db.call(QueryStr.str,"select @intOutIdx,@returnVal")

	for k,v in pairs(res1) do
		skynet.error(k,v)
	end
end

function lobby.CheckPlayerInAgentTable(pReq)
	QueryStr:Clean()
	QueryStr:AddStr("call pr_CheckPlayerInAgentTable2(")
	QueryStr:AddStr(math.floor(pReq.nPlayerID))
	QueryStr:AddStr(math.floor(pReq.nAgentID))
	QueryStr:AddOutParam("@intOutVal")
	QueryStr:AddOutParam("@returnVal")
	QueryStr:AddStr(")")
	local res1,res2 = db.call(QueryStr.str,"select @intOutVal,@returnVal")

	skynet.error("CheckPlayerInAgentTable = ",res2[1]['@intOutVal'])
	if res2 and res2[1]['@intOutVal'] == 1 then
		return true
	end

	return false
end

function lobby.AgentWriteScore(pReq)
	QueryStr:Clean()
	QueryStr:AddStr("call pr_WriteAgentGameScore2(")
	QueryStr:AddStr(math.floor(pReq.nAgentID))
	QueryStr:AddStr(math.floor(pReq.nTableID))
	QueryStr:AddStr(math.floor(pReq.nGameID))
	QueryStr:AddStr(math.floor(pReq.nCost))
	QueryStr:AddStr(math.floor(pReq.nPlayerCount))
	QueryStr:AddStr(math.floor(pReq.nTotalRound))
	QueryStr:AddStr(math.floor(pReq.nGameRound))
	QueryStr:AddOutParam("@intOutVal")
	QueryStr:AddOutParam("@returnVal")
	QueryStr:AddStr(")")
	local res1,res2 = db.call(QueryStr.str,"select @intOutVal,@returnVal")
end

return lobby